package com.ehais.util;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;

import com.ehais.modbuswifi.MyApplication;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.OnPermissionPageCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class WifiApUtil {

    public static final String TAG = WifiApUtil.class.getSimpleName();

    public static boolean statusWifiAp(){
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            try{
                WifiManager mWifiManager = (WifiManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                Method methodWifiApState = mWifiManager.getClass().getMethod("getWifiApState");
                int getWifiApState = (Integer) methodWifiApState.invoke(mWifiManager);
                // 获取属性值
                Field field = mWifiManager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
                int value = (int) field.get(mWifiManager);
                if (getWifiApState == value) {
                    Log.d(TAG, "热点已开启");
                    return true;
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    // wifi热点开关
    public static void setWifiApEnabled(boolean isEnable) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            Log.d(TAG, "安卓6.0及以下，使用setWifiApEnabled反射，开启关闭热点。");

            WifiManager mWifiManager = (WifiManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

            try {
                Method methodWifiApState = mWifiManager.getClass().getMethod("getWifiApState");
                int getWifiApState = (Integer) methodWifiApState.invoke(mWifiManager);

                // 获取属性值
                Field field = mWifiManager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
                int value = (int) field.get(mWifiManager);

                if (isEnable) {
                    if (getWifiApState == value) {
                        Log.d(TAG, "热点已开启");
                        return;
                    }
                }

                Method methodWifiApConfiguration = mWifiManager.getClass().getMethod("getWifiApConfiguration");
                WifiConfiguration mWifiConfiguration = (WifiConfiguration) methodWifiApConfiguration.invoke(mWifiManager);
                mWifiConfiguration.SSID="BPMS_AP";//热点名称
                mWifiConfiguration.preSharedKey="1234567890";//热点密码
                Method methodWifiApEnabled = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
                boolean flag = (Boolean) methodWifiApEnabled.invoke(mWifiManager, mWifiConfiguration, isEnable);
                Log.d(TAG, "热点" + (isEnable ? "开启" : "关闭") + "操作状态：" + flag);

//                NetworkUtils.numericToInetAddress("192.168.43.2");//设置网关

                if (flag) {
                    if (isEnable) {
                        Log.d(TAG, "热点成功开启");
                    }
                }

                if(mWifiManager != null){
                    WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
                    if (wifiInfo != null) {
                        String macAddress = wifiInfo.getMacAddress();
                        Log.d(TAG, "热点MAC地址"+macAddress);
                    }

                }

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            return;
        }

        TestOreoWifiManager mTestOreoWifiManager = new TestOreoWifiManager();
        if (isEnable) {
            Log.d(TAG, "安卓7.0以上，以proxy实现，开启关闭热点。");

            TestOreoWifiManager.TestOnStartTetheringCallback mCallback = new TestOreoWifiManager.TestOnStartTetheringCallback() {
                @Override
                public void onTetheringStarted() {
                    Log.d(TAG, "热点开启状态：" + "onTetheringStarted");
                }

                @Override
                public void onTetheringFailed() {
                    Log.d(TAG, "热点开启操作状态：" + "onTetheringFailed。");
                    Log.d(TAG, "onTetheringFailed");
                }
            };
            mTestOreoWifiManager.startTethering(mCallback);

        } else {
            mTestOreoWifiManager.stopTethering();
        }
    }

    // 关闭热点
    public static void closeWifiAp() {
        WifiApUtil.setWifiApEnabled(false);
    }



    public static void requestSystemSetPermissionAndOptionWifiAp(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            // 安卓6.0以下，不需要申请权限
            WifiApUtil.setWifiApEnabled(true);
        } else {
            // 安卓6.0及以上，需要申请修改系统设置权限
            XXPermissions.with(context).permission(Permission.WRITE_SETTINGS).request(new OnPermissionCallback() {
                @Override
                public void onGranted(List<String> permissions, boolean all) {
                    if (all) {
                        // 已有权限，开启本地热点
                        WifiApUtil.setWifiApEnabled(true);
                    }
                }

                @Override
                public void onDenied(List<String> permissions, boolean never) {
                    // 用户已禁止权限，弹框提示
                    // 用户同意再次请求权限
                    XXPermissions.startPermissionActivity((Activity) context, permissions, new OnPermissionPageCallback() {
                        @Override
                        public void onGranted() {
                            requestSystemSetPermissionAndOptionWifiAp(context);
                        }

                        @Override
                        public void onDenied() {
                            requestSystemSetPermissionAndOptionWifiAp(context);
                        }
                    });
                }
            });
        }
    }


    //获取链接到当前热点的设备IP
    public static ArrayList<String> getConnectedHotIP() {
        ArrayList<String> connectedIP = new ArrayList<String>();
        try {
            BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] splitted = line.split(" +");
                if (splitted != null && splitted.length >= 4) {
                    String ip = splitted[0];
                    if(!ip.equals("IP"))connectedIP.add(ip);
//                    Log.d(TAG,"---->> ip="+ip);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connectedIP;
    }

    //输出链接到当前设备的IP地址
    public static void printHotIp() {
        ArrayList<String> connectedIP = getConnectedHotIP();
        StringBuilder resultList = new StringBuilder();
        for (String ip : connectedIP) {
            resultList.append(ip);
            resultList.append("\n");
        }
        System.out.print(resultList);
        Log.d(TAG,"---->>heww resultList="+resultList);
    }



    public static String getIPAddress() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress() && addr instanceof Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            Log.e("getIPAddress", e.toString());
        }
        return "";
    }


}

